package com.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.hibernate.basedao.BaseDao;
import com.mytest.model.User;
import com.service.UserService;

public class UserServiceImpl implements UserService
{
    private static final long serialVersionUID = 1L;
    private final Logger      logger	   = Logger.getLogger(this.getClass());

    public BaseDao<User>      userDao	  = null;

    public User getUserById(Integer userId) throws Exception{
    	User user = null;
		try {
			user = userDao.get(userId);
		} catch (Exception e) {
		    logger.error("UserServiceImpl error:", e);
		    throw e;
		}
		return user;
    }
    
    public int saveOrUpdate(User user) throws Exception{
		try {
		    if (user == null) {
		    	return -1;
		    }
	
		    if (user.getUserId() == null) {
		    	user.setUserId(userDao.getNextId(User.class));
		    }
		    userDao.saveOrUpdate(user);
		} catch (Exception e) {
		    logger.error("UserServiceImpl error:", e);
		    throw e;
		}
		return 1;
    }

    public List<User> findUser(String userName, String password) throws Exception{
		List<User> userList = null;
		try {
		    if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)) {
		    	return null;
		    }
		    Map<String, String> map = new HashMap<String, String>();
		    map.put("userName", userName);
		    map.put("password", password);
		    userList = userDao.find(map);
		    //userList = userDao.find("from User where userName=? and password=?",new String[]{userName,password});//方法二
		} catch (Exception e) {
		    logger.error("UserServiceImpl error:", e);
		    throw e;
		}
		return userList;
    }

    public BaseDao<User> getUserDao(){
    	return userDao;
    }

    public void setUserDao(BaseDao<User> userDao){
    	this.userDao = userDao;
    }
}
